package alipay

import (
	"net/http"

	"github.com/smartwalle/alipay/v3"

	"mxshop-api/order-web/global"
)

// Alipay implements an alipay payment.
type Alipay struct {
	cli *alipay.Client
}

// NewAlipay creates an Alipay.
func NewAlipay(client *alipay.Client) *Alipay {
	return &Alipay{cli: client}
}

func NewTrade() alipay.Trade {
	conf := global.ServerConfig.AlipayConfig
	return alipay.Trade{
		NotifyURL:   conf.NotifyURL,
		ReturnURL:   conf.ReturnURL,
		ProductCode: conf.ProductCode,
	}
}

func NewTradePagePay() alipay.TradePagePay {
	return alipay.TradePagePay{
		Trade: NewTrade(),
	}
}

// Payment according to the payment condition returns payment URL.
func (a *Alipay) Payment(outTradeNo, amount, _ string) (string, error) {
	var p = NewTradePagePay()
	p.Subject = "生鲜超市订单-" + outTradeNo
	p.OutTradeNo = outTradeNo
	p.TotalAmount = amount

	url, err := a.cli.TradePagePay(p)
	if err != nil {
		return "", err
	}
	return url.String(), nil
}

func (a *Alipay) Notification(request *http.Request) (*alipay.TradeNotification, error) {
	return a.cli.GetTradeNotification(request)
}

func (a *Alipay) TradeQuery(orderSn string) (*alipay.TradeQueryRsp, error) {
	param := alipay.TradeQuery{OutTradeNo: orderSn}
	return a.cli.TradeQuery(param)
}
